﻿using System.Data.Entity;
using System.Linq;
using AdAggregator.Monitoring;
using ClothingAggregator.Models.Monitoring;

namespace ClothingAggregator.Models
{
    public class MonitoringContext : DbContext
    {
        public DbSet<MyMonitoringTask> MonitoringTasks { get; set; }
        public DbSet<MyMonitoringResult> MonitoringResults { get; set; }
        public DbSet<MyAdvertisement> Advertisements { get; set; }

        public MonitoringContext()
            : base("name=MonitoringContext")
        {
        }

        public bool AddNewMonitoringTask(IMonitoringTask newTask)
        {
            var dbTask = MonitoringTasks.FirstOrDefault(mt => mt.Id == newTask.Id);
            if (dbTask == null)
            {
                MonitoringTasks.Add(new MyMonitoringTask(newTask));
                SaveChanges();
                return true;
            }
            return false;
        }

        public void AddNewMonitoringResult(IMonitoringResult<MyAdvertisement> newResult)
        {
            AddNewAdvertisement(newResult.PricedAdvertisement);
            MonitoringResults.Add(new MyMonitoringResult(newResult));
            SaveChanges();
        }

        public void AddNewAdvertisement(MyAdvertisement ad)
        {
            Advertisements.Add(ad);
            SaveChanges();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<MyMonitoringTask>()
                        .HasMany(t => t.History)
                        .WithRequired()
                        .HasForeignKey(i => i.MonitoringTaskId)
                        .WillCascadeOnDelete(true);

            modelBuilder.Entity<MyAdvertisement>().Ignore(a => a.Source);

            modelBuilder.Entity<MyMonitoringResult>()
                .HasRequired(r => r.Advertisement)
                .WithRequiredDependent()
                .WillCascadeOnDelete(true);

        }
    }
}